import com.alibaba.moco.RedisPoolInstance
import com.alibaba.moco.util.BaseTypeUtil
import groovy.json.JsonOutput
import redis.clients.jedis.Jedis
import script.moco.dto.SetExceptionRequest
import script.moco.dto.SetExceptionResponse


//指定接口异常返回
def excute(data) {

    //固定借口
    def commandArr = ["createId", "createOrder", "cancelOrder", "feeConfirm", "complaint", "getOrderInfo", "comment", "getToken"];

    Jedis redis = RedisPoolInstance.getRedisClient();
    def params = data.getParameterMap();
    def request = BaseTypeUtil.mapToBean(params, SetExceptionRequest.class) as SetExceptionRequest;//请求数据转换为对象

    //定义响应对象
    def response = new SetExceptionResponse();

    //请求命令为clear时清楚所有接口异常
    if ("clear".equalsIgnoreCase(request.getInterfaces())) {

        redis.del("exception");

        response.setSuccess("true");
        response.setErrorMsg(null);
        response.setErrorCode(0);
        response.setErrorLevel(0);
        response.setContent(null);

        return response;
    }



    def jsonMap = redis.hgetAll("exception");

    //如果exception不存在则创建一个
    if (jsonMap == null) {
        jsonMap = [:];
    }

    def exitFlg = false;
    for (def i = 0; i < commandArr.size(); i++) {
        if (request.getInterfaces().equalsIgnoreCase(commandArr.get(i))) {
            exitFlg = true;
            break;
        }
    }

    //传入参数不属于指定借口抛出异常
    if (!exitFlg) {
        response.setSuccess("true");
        response.setErrorMsg("指定接口不存在");
        response.setErrorCode(39002);
        response.setErrorLevel(1);

        return response;
    }

    //将本次需要抛出exception的借口异常信息保存
    def exMap = [:]
    exMap.put("errno", request.getErrorCode())
    exMap.put("errmsg", request.getErrorMsg())
    exMap.put("data", null)
    jsonMap.put(request.getInterfaces(), JsonOutput.toJson(exMap).toString());

    //将信息保存至Redis
    redis.hmset("exception", jsonMap);



    response.setSuccess("true");
    response.setErrorMsg(null);
    response.setErrorCode(0);
    response.setErrorLevel(0);
    response.setContent(null);

    return response;
}